<template>
  <div id="counter">
      <div class="counter-box">
          <button class="counter-btn" @click="changeNum(-1)">-</button>
          <input v-model="amount" type="text" class="counter-input">
          <button class="counter-btn" @click="changeNum(1)">+</button>
      </div>
  </div>
</template>

<script>
export default {
    data:function(){
        return {
            num:this.amount
        }
    },
    props:['amount'],
    methods:{
        changeNum(num){
            var sum = this.num + num;
            if(sum < 0){
                sum = 0;
            }
            this.num = sum;
            this.$emit("changeCounter",this.num);
        }
    },
    watch:{
        'amount':{//监听amount的变化，如果发生变化，同步到num上，并出发事件
            handler(newVal){
                this.num = newVal;
                this.$emit("changeCounter",this.num);
            }
        }
    }
}
</script>


<style>

</style>